<?php

class CKEditorWidget extends CInputWidget {

    public $assets;
    public $model;
    public $attribute;
    
    public $name;
    public $value;
    public $config;
    public $folderID;
    public $paramsElFinder;

    public function init() {
        parent::run();
        Yii::app()->getAssetManager()->newFileMode = 0644; //fix bug on Matbao hosting
        Yii::app()->getAssetManager()->newDirMode = 0755; //fix bug on Matbao hosting
        
        $this->assets = Yii::app()->getAssetManager()
            ->publish(dirname(__FILE__) . 
                DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR
            );
        $this->setElFinder();
    }

    public function run() {
        $clientScript = Yii::app()->getClientScript();
        
        //register file
        $ckeditorUrl = $this->assets . '/ckeditor/ckeditor.js';
        $clientScript->registerScriptFile($ckeditorUrl, CClientScript::POS_HEAD);
        
        //render textarea
        echo CHtml::activeTextArea($this->model, $this->attribute);
        
        //run script
        $editorId = get_class($this->model) . '_' . $this->attribute;
        $txtConfig = $this->convertJsArray($this->config);
            
        $script = "
            CKEDITOR.replace( '$editorId', $txtConfig)
        ";
        
        $clientScript->registerScript(
            'ckeditor' . $this->attribute,
            $script,
            CClientScript::POS_READY
        );
    }

    /**
     * Set ElFinder configuration
     * @return void
     */
    private function setElFinder() {
        if ( isset($this->model->params) ) {
            $params = $this->model->params;
        } else {
            $params = Yii::app()->params['newsletter_image'];
        }
        
        //create folder
        if (! empty($this->folderID)) {
            $dir = $params['upload_dir'] . $this->folderID;
            $params['elfinder']['base_path'] .= $this->folderID . '/';
            $params['elfinder']['base_url'] .= $this->folderID . '/';
            
            if (! file_exists($dir)) {
                mkdir($dir);
            }
        }
        
        //set $_SESSION
        if ( (isset($this->config['toolbar'])) && ($this->config['toolbar'] != '') ) {
            Yii::app()->session['elfinder'] = $params;
            $this->config['filebrowserBrowseUrl'] = $this->assets
                . '/elfinder_v2.0/elfinder.php?type=file';
            $this->config['filebrowserImageBrowseUrl'] = $this->assets
                . '/elfinder_v2.0/elfinder.php?type=image';
            $this->config['filebrowserFlashBrowseUrl'] = $this->assets
                . '/elfinder_v2.0/elfinder.php?type=flash';
        }
    }
    
    /**
     * Convert php array to JS format
     * @param array $phpArray
     * Ex:
     *  array(
     *      'name' => 'le dat',
     *      'pass' => '123',
     *  )
     * Convert To
     *  { name: 'le dat', pass: '123' }
     */
    private function convertJsArray($phpArray) {
        $result = '';
        
        foreach ($phpArray as $key=>$value) {
            $result .= $key . ':' . "'$value'" . ',';
        }
        
        return '{'. rtrim($result) .'}';
    }
    
    /**
     * Set Local file manager configuration
     * @return void
     */
//    private function setLocalFinder() {
//        $this->config['filebrowserImageBrowseUrl'] = '/public/backend/dadmin/comImgMan';
//    }
}